package cn.keduox.utils;

/**
 * Created by Administrator on 2017/12/4 0004.
 */

import java.sql.*;


/**
 * c3p0连接池工具类
 */
public class JDBCUtils {
    //初始化链接池
    static {
        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //从连接池中获取连接
    public static Connection getConnection() throws SQLException {
        Connection connection=DriverManager.getConnection("jdbc:mysql:///book_china","root","235145");
        return connection;
    }

    //封装占位符
    public static PreparedStatement setObject(PreparedStatement preparedStatement, Object... objects) {
        for (int i = 0; i < objects.length; i++) {
            try {
                preparedStatement.setObject(i + 1, objects[i]);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return preparedStatement;
    }

    //关闭资源
    public static void close(Connection conn, Statement preparedStatement, ResultSet resultSet) {
            //关闭连接
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        if (preparedStatement != null) {
            //关闭预编译语句
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (resultSet != null) {
            //关闭结果集
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}
